package util;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidTouchAction;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import modules.FlyReaderModule;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.csvreader.CsvWriter;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class CommonUtil {

    public AppiumDriver driver;

    /**
     * 调用启动App
     * @throws Exception
     */
    public AppiumDriver startApp(String deviceName, String platformVersion) {
        DesiredCapabilities cap = new DesiredCapabilities();

        cap.setCapability(CapabilityType.BROWSER_NAME, "");
        cap.setCapability("platformName", "Android");
        cap.setCapability("deviceName", deviceName);
        cap.setCapability("platformVersion", platformVersion);
        cap.setCapability("appPackage", "com.yuewen.cooperate.reader.free");
        cap.setCapability("appActivity", "com.qq.reader.activity.SplashActivity");
        //A new session could not be created的解决方法
        cap.setCapability("appWaitActivity", "com.qq.reader.activity.SplashActivity");
        //每次启动时覆盖session，否则第二次后运行会报错不能新建session
        cap.setCapability("sessionOverride", true);
        try {
            driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);
        } catch (MalformedURLException e) {
            System.out.println("启动APP报错。。。");
            e.printStackTrace();
        }
        return driver;
    }

    /**
     * 向上滑动滑动
     * @param number
     */
    public void swipeToup(int number){
        TouchAction<AndroidTouchAction> tAction = new AndroidTouchAction(driver);
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        int time = (int) (3*1000);
        Duration durationTime = Duration.ofNanos(time);
        for(int i=0;i<number;i++){
            tAction.press(PointOption.point(width / 2, 3 / 4))
                    .waitAction(WaitOptions.waitOptions(durationTime))
                    .moveTo(PointOption.point(width / 2, height * 1 / 4))
                    .release().perform();
        }
    }
    /**
     * 向下滑动滑动
     */
    public void swipLow(){
        TouchAction<AndroidTouchAction> tAction = new AndroidTouchAction(driver);
        int width = driver.manage().window().getSize().width;
        int height = driver.manage().window().getSize().height;
        int time = (int) (3*1000);
        Duration durationTime = Duration.ofNanos(time);
        tAction.press(PointOption.point(width / 2, 1 / 4))
                .waitAction(WaitOptions.waitOptions(durationTime))
                .moveTo(PointOption.point(width / 2, height * 3 / 4))
                .release().perform();
    }

    /**
     * 判断元素存不存在
     * @param by
     * @return
     */
    public boolean byElementIsExist(By by) {
        try {
            driver.findElement(by);
            return false;
        } catch (Exception e) {
            return true;
        }
    }


    /**
     *  导入本地CSV
     * @param flyReadAllinformation
     */
    public void csvWrite(List<FlyReaderModule> flyReadAllinformation){
        String csvFilePath = "C:\\Users\\yanmei\\Desktop\\bookTest.csv";
        try {
            // 创建CSV写对象 例如:CsvWriter(文件路径，分隔符，编码格式);
            CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("GBK"));
            // 写内容
            String[] headers = {"当前频道","当前模块","性别","书名","作者","版权"};
            csvWriter.writeRecord(headers);
            for (int i=0;i< flyReadAllinformation.size();i++){
                FlyReaderModule flyReaderModuleWriet = new FlyReaderModule();
                flyReaderModuleWriet=flyReadAllinformation.get(i);
                String[] bookdetail ={flyReaderModuleWriet.getChannel(),flyReaderModuleWriet.getModelName(),flyReaderModuleWriet.getSex(),
                        flyReaderModuleWriet.getBookName(),flyReaderModuleWriet.getAuthorName(),flyReaderModuleWriet.getCopyright()};
                csvWriter.writeRecord(bookdetail);
            }
            csvWriter.close();
            System.out.println("--------CSV文件已经写入--------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 频道名称
     */
    public String channelName(String name,int number){
        String channelName="";
        List<WebElement> channelList = new ArrayList<WebElement>();
        driver.findElement(By.name(name)).click();
        //channelList = driver.findElements(By.id(id));
        //channelName=channelList.get(number).getText();
        return channelName;
    }

    /**
     *  书籍去重
     * @param bookname
     * @return
     */
    public boolean distance(String bookname,List<FlyReaderModule> flyReadAllinformation){
        for(int j=0;j<flyReadAllinformation.size();j++){
            FlyReaderModule flyModule=flyReadAllinformation.get(j);
            if(bookname.equals(flyModule.getBookName())){
                return false;
            }
        }
        return true;
    }

    /**
     *  封装睡眠等待
     * @param time
     */
    public void sleep(long time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
